import Viewer from "viewerjs";

export function bindImgClick() {
    const elems = document.getElementsByClassName("md-editor-preview");
    for (let i = 0; i < elems.length; i++) {
        const imgList = elems[i].querySelectorAll("img");
        if (imgList.length > 0) {
            for (let j = 0; j < imgList.length; j++) {
                if (imgList[j].getAttribute("isBind") === true) {
                    continue;
                }
                imgList[j].onclick = () => {
                    preViewCover(elems[i]);
                };
                imgList[j].setAttribute("isBind", true);
            }
        }

        // === 新增：为所有链接添加 target="_blank" ===
        const linkList = elems[i].querySelectorAll("a[href]");
        for (let j = 0; j < linkList.length; j++) {
            const link = linkList[j];
            if (link.getAttribute("isBind") === true) {
                continue;
            }
            link.target = '_blank';
            link.rel = 'noopener noreferrer';
            link.setAttribute("isBind", true);
        }
    }
}

function preViewCover(elem) {
    const viewer = new Viewer(elem, {
        title: false,
        hide: () => {
            viewer.destroy();
        },
    });
    viewer.show();
}
